package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @Author LA
 * @Date 2024/8/18 15:46
 * @Description: Redis分布式锁实现
 */
public class SimpleRedisLock implements ILock{
    private String name;
    private StringRedisTemplate stringRedisTemplate;
    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }
    private static final String LOCK_PREFIX="lock:";
    private static final String ID_PREFIX= UUID.fastUUID().toString(true)+"-";
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT=new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));  //指定脚本文件的位置
        UNLOCK_SCRIPT.setResultType(Long.class); //配置返回值类型
    }

    @Override
    public boolean tryLock(long timeoutSeconds) {
        //获取当前执行线程标识
        String threadId = ID_PREFIX+Thread.currentThread().getId();
        //获取锁
        Boolean success = stringRedisTemplate.opsForValue()
                .setIfAbsent(LOCK_PREFIX+name, threadId, timeoutSeconds, TimeUnit.SECONDS);
        //Boolean是用于封装基本数据类型的对象类型，有三种取值状态：true  false  null
        //boolean是基本数据类型，不能调用方法，异也不能为null,只能直接存储true或false值
        //所以此处我们需要将Boolean转为boolean基本数据类型，如果直接返回可能会出现空指针异常
        //也可以使用工具类  return BooleanUtil.isTrue(success);
        return Boolean.TRUE.equals(success);
    }

    @Override
    public void unLock() {
        //基于Lua脚本释放锁（保证原子性）
                    //此处我们在上面的静态代码块去预加载一下我们的lua脚本
        stringRedisTemplate.execute(UNLOCK_SCRIPT,
                Collections.singletonList(LOCK_PREFIX+name),
                Collections.singletonList(ID_PREFIX+Thread.currentThread().getId()));
    }

/*    @Override
    public void unLock() {
        //获取线程标识
        String threadId = ID_PREFIX+Thread.currentThread().getId();
        //获取锁中的标识
        String string = stringRedisTemplate.opsForValue().get(LOCK_PREFIX + name);
        //判断标识是否一致
        if(threadId.equals(string)){
            //释放锁
            stringRedisTemplate.delete(LOCK_PREFIX+name);
        }
    }*/
}
